<template>
    <v-dialog v-model="dialogFormVisible" max-width="900px" persistent scrollable>
        <v-card class="elevation-10 pa-2">
            <v-card-title class="d-flex align-center"> 
                {{ title }}
            </v-card-title>

            <v-card-text>
                <v-form ref="formRef" v-model="formValid">
                    <v-row>
                       
                        <v-col cols="12" md="6">
                            <v-text-field
                                v-model="form.eventName"
                                :rules="rules.eventName"
                                density="compact"
                                hide-details="auto"
                                label="业务事件名称"
                                required
                                variant="outlined"
                                placeholder="如：缴费成功"
                            />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field
                                v-model="form.fromStatus"
                                :rules="rules.fromStatus"
                                density="compact"
                                hide-details="auto"
                                label="原状态编码"
                                required
                                variant="outlined"
                                placeholder="如：10（试听中）"
                            />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field
                                v-model="form.toStatus"
                                :rules="rules.toStatus"
                                density="compact"
                                hide-details="auto"
                                label="目标状态编码"
                                required
                                variant="outlined"
                                placeholder="如：11（已报名）"
                            />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-switch
                                :model-value="form.isAuto === 1"
                                @update:model-value="(val: boolean) => form.isAuto = val ? 1 : 0"
                                color="primary"
                                hide-details
                                label="是否自动流转"
                            />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field
                                v-model.number="form.sortOrder"
                                density="compact"
                                hide-details="auto"
                                label="排序号"
                                type="number"
                                variant="outlined"
                                placeholder="数字越小优先级越高"
                            />
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-switch
                                :model-value="form.isActive === 1"
                                @update:model-value="(val: boolean) => form.isActive = val ? 1 : 0"
                                color="primary"
                                hide-details
                                label="是否启用"
                            />
                        </v-col>
                        <v-col cols="12">
                            <v-textarea
                                v-model="form.conditions"
                                density="compact"
                                hide-details="auto"
                                label="流转条件(JSON格式)"
                                variant="outlined"
                                rows="4"
                                placeholder='{"amount": {">=": 1000}, "course": {"in": ["数学", "英语"]}}'
                            />
                            <v-card variant="outlined" class="mt-2 pa-2" color="info">
                                <v-card-text class="text-caption">
                                    <strong>条件格式说明：</strong><br>
                                    • 等于：{"field": "value"}<br>
                                    • 大于等于：{"amount": {">=": 1000}}<br>
                                    • 包含：{"course": {"in": ["数学", "英语"]}}<br>
                                    • 不等于：{"status": {"!=": "inactive"}}<br>
                                    • 多条件与：多个条件并列即为AND关系
                                </v-card-text>
                            </v-card>
                            
                            <v-card variant="outlined" class="mt-2 pa-2" color="success">
                                <v-card-text class="text-caption">
                                    <strong>完整案例 - 缴费成功触发状态流转：</strong><br>
                                    <v-code class="d-block mt-2 pa-2" style="background-color: #f5f5f5; border-radius: 4px; white-space: pre-wrap;">
{
  "amount": {">=": 500},
  "paymentMethod": {"in": ["alipay", "wechat", "bank"]},
  "courseType": "premium",
  "studentAge": {">=": 6, "<=": 18},
  "isFirstTime": true
}
                                    </v-code>
                                    <strong class="mt-2 d-block">说明：</strong>
                                    只有当客户满足以下全部条件时才会触发状态流转：<br>
                                    • 缴费金额 ≥ 500元<br>
                                    • 支付方式为支付宝、微信或银行转账<br>
                                    • 课程类型为高级课程<br>
                                    • 学生年龄在6-18岁之间<br>
                                    • 是首次报名的客户
                                </v-card-text>
                            </v-card>
                        </v-col>
                        <v-col cols="12">
                            <v-textarea
                                v-model="form.remark"
                                density="compact"
                                hide-details="auto"
                                label="备注"
                                variant="outlined"
                                rows="2"
                                placeholder="规则说明或使用场景"
                            />
                        </v-col>
                    </v-row>
                </v-form>
            </v-card-text>

            <v-card-actions>
                <v-spacer />
                <v-btn color="grey-darken-1" variant="text" @click="close"> 取消 </v-btn>
                <v-btn :loading="saving" color="primary" variant="text" @click="save"> 确定 </v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, onMounted } from 'vue';
import { doInsert, doUpdate, type TenantStatusRuleModel, type ApiResponse } from '@/api/tenant/customerstatus/TenantStatusRuleManagementApi';
import { isNull } from '@/utils/validate';
import { formateDate } from '@/utils/format';
import { useMessage } from '@/composables/useMessage';

const { success: showSuccess, error: showError } = useMessage();

// 基础数据
const dialogFormVisible = ref(false);
const title = ref('');
const formValid = ref(false);
const formRef = ref();
const saving = ref(false);
const defaultFrom: TenantStatusRuleModel = {

    eventName: '',
    fromStatus: '',
    toStatus: '',
    isAuto: 1,
    conditions: '',
    sortOrder: 0,
    isActive: 1,
    remark: ''
};

// 表单数据
const form = reactive<Partial<TenantStatusRuleModel>>(structuredClone(defaultFrom));

// 验证规则
const rules = {
   
    eventName: [(v: any) => !!v || '业务事件名称不能为空'],
    fromStatus: [
        (v: any) => !!v || '原状态编码不能为空',
        (v: any) => /^\d+$/.test(v) || '状态编码必须是数字'
    ],
    toStatus: [
        (v: any) => !!v || '目标状态编码不能为空',
        (v: any) => /^\d+$/.test(v) || '状态编码必须是数字'
    ]
};

// 事件发射
const emit = defineEmits<{
    fetchData: [];
}>();

// 显示编辑对话框
function showEdit(row?: TenantStatusRuleModel) {
    if (!row) {
        title.value = '添加状态流转规则';
        // 重置表单为默认值
        Object.assign(form, structuredClone(defaultFrom));
    } else {
        title.value = '编辑状态流转规则';
        // 复制行数据到表单
        const formData = { ...row };
        Object.assign(form, formData);
    }

    dialogFormVisible.value = true;
}

// 关闭对话框
function close() {
    dialogFormVisible.value = false;
    nextTick(() => {
        if (formRef.value) {
            formRef.value.reset();
        }
        // 重置表单数据
        Object.assign(form, structuredClone(defaultFrom));
    });
}

// 保存
async function save() {
    if (!formRef.value) return;

    try {
        const { valid } = await formRef.value.validate();
        if (!valid) return;

        // 验证JSON格式
        if (form.conditions) {
            try {
                JSON.parse(form.conditions);
            } catch (error) {
                showError('流转条件必须是有效的JSON格式');
                return;
            }
        }

        saving.value = true;

        // 处理表单数据
        const submitData = { ...form } as TenantStatusRuleModel;
        handlerFormData(submitData);

        let response: ApiResponse<TenantStatusRuleModel>;

        // 编辑模式
        if (!isNull(submitData.id)) {
            let { msg } = await doUpdate(submitData);
            showSuccess(msg || '更新成功');
        } else {
            // 新增模式
            let { msg } = await doInsert(submitData);
            showSuccess(msg || '添加成功');
        }

        // 通知父组件刷新数据
        emit('fetchData');
        close();
    } catch (error) {
        console.error('保存失败:', error);
        showError('保存失败');
    } finally {
        saving.value = false;
    }
}

// 处理表单数据
function handlerFormData(formData: any) {
    if (!isNull(formData)) {
        for (const key in formData) {
            // 对于时间类进行处理
            if (Object.prototype.toString.call(formData[key]) === '[object Date]') {
                formData[key] = formateDate(formData[key], 'yyyy-MM-dd hh:mm:ss');
            }
            // 处理datetime-local格式
            else if (typeof formData[key] === 'string' && formData[key].includes('T')) {
                formData[key] = formData[key].replace('T', ' ') + ':00';
            }
        }
    }
}

// 暴露方法
defineExpose({
    showEdit
});

// 生命周期
onMounted(() => {
    // 初始化
});
</script>

<style lang="scss" scoped>
:deep(.v-dialog) {
    .v-card-title {
        background-color: rgb(var(--v-theme-primary));
        color: white;
    }
}
</style> 

